package com.jack.controller;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import com.jack.aggragate.AggragationService;
import com.jack.entity.User;

import rx.Observable;
import rx.Observer;

@RestController
public class Aggragaioncontroller {
	
	private static final Logger logger = LoggerFactory.getLogger(Aggragaioncontroller.class);

	@Autowired
	private AggragationService aggragationService;
	
	@GetMapping("/aggragate/{id}")
	public DeferredResult<HashMap<String, User>> aggration(@PathVariable("id") Long id){
		Observable<HashMap<String, User>> result  = this.aggragationObservable(id);
		return this.toDeferredResult(result);
	}
	
	private Observable<HashMap<String, User>> aggragationObservable(Long id){
		return Observable.zip(this.aggragationService.getUserById(id),
				this.aggragationService.getMovieById(id), 
				(user, movieUser) ->{
					HashMap<String, User> map = new HashMap<String, User>();
					map.put("user", user);
					map.put("movieUser", movieUser);
					return map;
				});
	}
	
	private DeferredResult<HashMap<String, User>> toDeferredResult(Observable<HashMap<String, User>> details){
		DeferredResult<HashMap<String, User>> result = new DeferredResult<>();
		details.subscribe(new Observer<HashMap<String, User>>(){

			@Override
			public void onCompleted() {
				logger.info("finish");
				
			}

			@Override
			public void onError(Throwable e) {
				logger.error("error occur");
			}

			@Override
			public void onNext(HashMap<String, User> movieDetails) {
				result.setResult(movieDetails);
			}
			
		});
		return result;
	}
}
